<?php
namespace app;
use App;
class DefaultController extends BaseObject{

	public function beforeRoute(){
		$this->filterHeader();
		$flag = parent::beforeRoute();
		if(!empty(App::$app->session->get('access_keys'))){
			$akey = !empty(App::$app->request->get('akey')) ? strip_tags(preg_replace("/[^a-zA-Z0-9\._-]/", '', App::$app->request->get('akey'))) : '';
			if(empty($akey) && function_exists('checkAccess')){
				if(checkAccess()){
					return true;
				}
			}elseif (in_array($akey, App::$app->getOption('access_keys'))){
				if(function_exists('checkAccess') && checkAccess()){
					return true;
				}
				App::$app->f3->error(403);
			}
		}
		App::$app->f3->error(403);
	}
	public function filterHeader(){
		$domian = $_SERVER['HTTP_HOST'];
		$domian = str_replace('www.', '', $domian);
		$head_contents = [
			'default-src' => ['self', '*.'.$domian.'', '*.googletagmanager.com','*.google-analytics.com', '*.cloudflare.com'],
			'style-src' => ['self', 'unsafe-inline', '*.'.$domian.'', '*.googletagmanager.com','*.google-analytics.com'],
			'script-src' => ['self', 'unsafe-inline', 'unsafe-eval', '*.'.$domian.'', '*.googletagmanager.com','*.google-analytics.com','*.google.com', '*.googleadservices.com', '*.cloudflareinsights.com', 'googleads.g.doubleclick.net', '*.cloudflare.com'],
			'connect-src' => ['self', 'unsafe-inline', 'unsafe-eval', 'data:', 'blob:', '*.'.$domian.'', '*.googletagmanager.com','*.google-analytics.com','*.google.com'],
			'img-src' => ['self', 'unsafe-inline', 'unsafe-eval', 'data:', '*.'.$domian.'', '*.googletagmanager.com','*.google-analytics.com', 'googleads.g.doubleclick.net'],
			'font-src' => ['self', 'unsafe-inline', 'unsafe-eval', 'data:', '*.'.$domian.'', '*.googletagmanager.com','*.google-analytics.com'],
		];
		header('Content-Security-Policy:'.\app\utils\CspFilter::cspContent($head_contents));
		header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
	}
	
	public function actionIndex(){
		$manger = App::$app->fileManger;
		$path = App::$app->request->get('path');
		$files = $manger->index($path);
		$csrf = App::$app->csrf->create();
		$paths = !empty($path) ? explode('/', $path) : [];
		$breadcrumb = [];
		$p_path = [];
		$data = [];
		foreach ($paths as $key => $val) {
			$p_path[] = $val;
			$url = App::$app->request->to('./dialog.php', ['path'=>implode('/', $p_path)], false);

			$breadcrumb[] = [
				'label' => $val,
				'link' => $url,
			];
		}
		array_pop($p_path);
		$type_param = fix_get_params(App::$app->request->get('type'));
		$data['last_url'] = App::$app->request->to('./dialog.php', empty($p_path) ? ['path'=>''] : ['path'=>implode('/', $p_path)], false);
		$data['field_id'] = App::$app->request->get('field_id');
		if ($type_param == 1) {
			$apply_type = 'apply_img';
		} elseif ($type_param == 2) {
			$apply_type = 'apply_link';
		} elseif ($type_param == 0 && !$data['field_id']) {
			$apply_type = 'apply_none';
		} elseif ($type_param == 3) {
			$apply_type = 'apply_video';
		} else {
			$apply_type = 'apply';
		}
		$data['apply_type'] = $apply_type;
		$data['cur_dir'] = App::$app->path->getCurDir($path);
		$data['base_url'] = App::$app->getOption('base_url');
		$data['max_upload_files'] = App::$app->getOption('max_upload_files');
		$data['max_upload_files'] = $data['max_upload_files'] ?: 10;
		$data['return_relative_url'] = App::$app->request->get('relative_url') == 1 ? 1 : 0;
		$data['callback'] = !empty(App::$app->request->get('callback')) ? App::$app->request->get('callback') : 0;
		$data['ext_img'] = implode("','", App::$app->getOption('ext_img'));
		App::$app->f3->set('data', $data);
		App::$app->f3->set('lists', $files);
		App::$app->f3->set('path', $path);
		App::$app->f3->set('breadcrumb', $breadcrumb);
		App::$app->f3->set('csrf', $csrf);
		$view = new \Template();
		echo $view->render('libs/views/index.html');
	}
	public function actionUpload(){
		header('Content-Type:application/json; charset=utf-8');
		if(!App::$app->csrf->validate(App::$app->request->post(), false)){
			throw new \Exception("Error Processing Request", 405);			
		}
		switch (App::$app->request->post('type')) {
			case 'do':
			$flag = App::$app->fileManger->put($_FILES['file'], App::$app->request->post('path'), ['water'=>App::$app->request->post('water'), 'position'=>App::$app->request->post('position')]);
			echo json_encode(['status'=>(int)$flag, 'msg'=>$flag ? 'Success' : 'Fail']);
			exit();
			break;
			case 'dom':
			$flag = App::$app->fileManger->mkdir(App::$app->request->post('new_folder'), App::$app->request->post('path'));
			echo json_encode(['status'=>(int)$flag, 'msg'=>$flag ? 'Success' : 'Fail']);
			exit();
			break;
			case 'dod':
			$flag = App::$app->fileManger->delete(App::$app->request->post('name'), App::$app->request->post('path'));
			echo json_encode(['status'=>(int)$flag, 'msg'=>$flag ? 'Success' : 'Fail']);
			exit();
			break;
			case 'dor':
			$flag = App::$app->fileManger->rename(App::$app->request->post('file_id'), App::$app->request->post('name'), App::$app->request->post('path'));
			echo json_encode(['status'=>(int)$flag, 'msg'=>$flag ? 'Success' : 'Fail']);
			exit();
			break;
			
			default:
				// code...
			break;
		}
	}
	public function test(){
		$path = '../ddddd';
		var_dump(stripos($path, '..'));
		exit();
		// header('Content-Type:application/json; charset=utf-8');
		// echo json_encode(['status'=>1, 'msg'=>'Success']);
	}
}